package com.yourname.myapplication.activity

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.yourname.myapplication.database.AppDatabase
import com.yourname.myapplication.model.StudyRecord
import com.yourname.myapplication.ui.theme.MyApplicationTheme
import com.yourname.myapplication.viewmodel.StudyRecordViewModel
import java.text.SimpleDateFormat
import java.util.*

class StudyRecordActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                val viewModel: StudyRecordViewModel = viewModel(
                    factory = androidx.lifecycle.viewmodel.viewModelFactory {
                        // 直接实例化 ViewModel
                        StudyRecordViewModel(
                            AppDatabase.getInstance(applicationContext)
                        )
                    }
                )
                val userId = 1 // 这里需要根据实际情况获取用户 ID
                val records by viewModel.getRecordsByUserId(userId).collectAsState(initial = emptyList())
                StudyRecordScreen(records)
            }
        }
    }
}

@Composable
fun StudyRecordScreen(records: List<StudyRecord>) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(text = "学习记录", fontWeight = FontWeight.Bold, modifier = Modifier.padding(bottom = 16.dp))
        LazyColumn {
            items(records) { record ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 16.dp),
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(text = "分类: ${record.category}", fontWeight = FontWeight.Bold)
                        Text(text = "题目数量: ${record.questionCount}")
                        Text(text = "正确数量: ${record.correctCount}")
                        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
                        Text(text = "日期: ${dateFormat.format(record.date)}")
                    }
                }
            }
        }
    }
}